package com.example.demo.component.decorator;



import com.example.demo.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;
import java.util.UUID;

/**
 * @author liguang03
 * @create 2022/10/21
 */
public class MdcTaskDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String, String> map = MDC.getCopyOfContextMap();

        return () ->{
            try{
                MDC.setContextMap(map);
                String traceId = MDC.get(Constants.REQUEST_ID);
                if(StringUtils.isBlank(traceId)){
                    traceId = UUID.randomUUID().toString();
                    MDC.put(Constants.REQUEST_ID, traceId);
                }
                runnable.run();
            }finally {
                MDC.remove(Constants.REQUEST_ID);
            }
        };
    }
}
